﻿using System;
using System.IO;
using log4net;
using Matrix.Common.Utility.Files;
using Matrix.MaKaYunShang.DAL.DalExt;
using Matrix.MaKaYunShang.Model.DataStatisticsModels;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;
using System.Data;

namespace Matrix.MaKaYunShang.BLL.BllExt
{
    public class GfcStatBll
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(GfcStatBll));
        private readonly GfcStatDal _gfcStatDal = new GfcStatDal();

        #region 订单详情统计报表
        /// <summary>
        /// 订单详情统计报表
        /// </summary>
        /// <param name="draw">分页计数器</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页显示数量</param>
        /// <param name="dtBeginTime">查询开始日期（可选）</param>
        /// <param name="dtEndTime">查询结束日期（可选）</param>
        /// <param name="shopId">查询店铺ID（可选）</param>
        /// <returns></returns>
        public TableDataViewDto<FullDataStatOrderDetail> QueryStatOrderDetailInfoPage(int draw, int pageIndex = 1,
            int pageSize = 50, DateTime? dtBeginTime = null, DateTime? dtEndTime = null, int? shopId = null)
        {
            var totalCount = 0;
            pageIndex = pageIndex <= 0 ? 1 : pageIndex;
            pageSize = pageSize <= 0 ? 50 : pageSize;

            if (dtBeginTime != null && dtEndTime != null)
            {
                if ((DateTime)dtBeginTime > (DateTime)dtEndTime)
                {
                    var dtTemp = dtEndTime;
                    dtEndTime = dtBeginTime;
                    dtBeginTime = dtTemp;
                }
            }

            try
            {
                var dataStatDetailList = _gfcStatDal.QueryStatOrderDetailInfo<FullDataStatOrderDetail>(true, ref totalCount,
                dtBeginTime, dtEndTime, shopId, pageIndex, pageSize);
                var returnDataList = new TableDataViewDto<FullDataStatOrderDetail>
                {
                    data = dataStatDetailList,
                    draw = draw,
                    recordsFiltered = totalCount,
                    recordsTotal = totalCount
                };
                return returnDataList;
            }
            catch (Exception ex)
            {
                _fileLog.Error("GfcStatBll | QueryStatOrderDetailInfoPage | Exception: " + ex);
                return null;
            }
        }

        /// <summary>
        /// 到处订单详情统计报表EXCEL文件
        /// </summary>
        /// <param name="xlsxFilePath">文件路径</param>
        /// <param name="dtBeginTime">查询开始日期（可选）</param>
        /// <param name="dtEndTime">查询结束日期（可选）</param>
        /// <param name="shopId">查询店铺ID（可选）</param>
        public bool ExportExcelStatOrderDetailInfo(string xlsxFilePath, DateTime? dtBeginTime = null,
            DateTime? dtEndTime = null, int? shopId = null)
        {
            if (string.IsNullOrWhiteSpace(xlsxFilePath))
            {
                return false;
            }

            if (dtBeginTime != null && dtEndTime != null)
            {
                if ((DateTime)dtBeginTime > (DateTime)dtEndTime)
                {
                    var dtTemp = dtEndTime;
                    dtEndTime = dtBeginTime;
                    dtBeginTime = dtTemp;
                }
            }
            try
            {
                var totalCount = 0;
                var dataStatDetailList = _gfcStatDal.QueryStatOrderDetailInfo<BaseDataStatOrderDetail>(false, ref totalCount, dtBeginTime, dtEndTime, shopId);
                if (dataStatDetailList == null || dataStatDetailList.Count == 0)
                {
                    return false;
                }
                DataSet ds = new DataSet();
                ds.Tables.Add(CreateExcelFile.ListToDataTable(dataStatDetailList));
                ds.Tables[0].Columns[0].ColumnName = "销售时间";
                ds.Tables[0].Columns[1].ColumnName = "订单编号";
                ds.Tables[0].Columns[2].ColumnName = "微信端支付流水号";
                ds.Tables[0].Columns[3].ColumnName = "商品条形码";
                ds.Tables[0].Columns[4].ColumnName = "商品名称";
                ds.Tables[0].Columns[5].ColumnName = "商品计量单位";
                ds.Tables[0].Columns[6].ColumnName = "商品规格";
                ds.Tables[0].Columns[7].ColumnName = "销售数量";
                ds.Tables[0].Columns[8].ColumnName = "商品单价";
                ds.Tables[0].Columns[9].ColumnName = "实收金额";
                ds.Tables[0].Columns[10].ColumnName = "立减金额";
                ds.Tables[0].Columns[11].ColumnName = "支付方式";
                ds.Tables[0].Columns[12].ColumnName = "店铺名称";
                ds.Tables[0].Columns[13].ColumnName = "售卖方式";
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/")))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/"));
                }
               return CreateExcelFile.CreateExcelDocument(ds, xlsxFilePath);
            }
            catch (Exception ex)
            {
                _fileLog.Error("GfcStatBll | ExportExcelStatOrderDetailInfo | Exception: " + ex);
                return false;
            }
        }
        #endregion

        #region 数据统计报表
        /// <summary>
        /// 统计码云卡销售数据
        /// 可选择 分店铺 分商品 分统计周期 分用户 分配送人员进行统计
        /// 可指定时间段 指定店铺ID 指定用户ID 指定商品名 指定商品条形码 指定配送人员进行查询
        /// </summary>
        /// <param name="draw">分页计数器</param>
        /// <param name="queryDateType">查询时间周日类别</param>
        /// <param name="isGroupbyShop">是否分店铺查询</param>
        /// <param name="isGroupByCommodity">是否分商品查询</param>
        /// <param name="isGroupByPayWay">是否分支付方式查询</param>
        /// <param name="isGroupByConsumer">是否分用户查询</param>
        /// <param name="isGroupByDeliveryAccount">是否分配送人员查询</param>
        /// <param name="dtBeginTime">开始时间</param>
        /// <param name="dtEndTime">结束时间</param>
        /// <param name="shopId">店铺ID</param>
        /// <param name="orderPayWay">支付方式</param>
        /// <param name="commodityName">商品名称</param>
        /// <param name="commodityBarCode">商品条形码</param>
        /// <param name="deliveryAccountId">配送人员ID</param>
        /// <param name="consumerName">客户名称</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页显示数量</param>
        /// <returns></returns>
        public TableDataViewDto<T> QueryStatShopCommoditySellingPage<T>(int draw,
            CommonEnum.DataStatQueryDateType queryDateType, bool isGroupbyShop = false,
            bool isGroupByCommodity = false, bool isGroupByPayWay = false, bool isGroupByConsumer = false,
            bool isGroupByDeliveryAccount = false, DateTime? dtBeginTime = null, DateTime? dtEndTime = null,
            int? shopId = null, int? orderPayWay = null, string commodityName = "", string commodityBarCode = "",
            int? deliveryAccountId = null, string consumerName = null, int pageIndex = 1, int pageSize = 50)
        {
            var totalCount = 0;
            pageIndex = pageIndex <= 0 ? 1 : pageIndex;
            pageSize = pageSize <= 0 ? 50 : pageSize;
            if (dtBeginTime != null && dtEndTime != null)
            {
                if ((DateTime)dtBeginTime > (DateTime)dtEndTime)
                {
                    var dtTemp = dtEndTime;
                    dtEndTime = dtBeginTime;
                    dtBeginTime = dtTemp;
                }
            }
            if (deliveryAccountId != null && deliveryAccountId>0)
            {
                isGroupByDeliveryAccount = true;
            }
            if (!string.IsNullOrEmpty(consumerName))
            {
                isGroupByConsumer = true;
            }
            if (orderPayWay != null)
            {
                isGroupByPayWay = true;
            }
            if (!string.IsNullOrWhiteSpace(commodityName) || !string.IsNullOrWhiteSpace(commodityBarCode))
            {
                isGroupByCommodity = true;
            }
            if (shopId != null && shopId>0)
            {
                isGroupbyShop = true;
            }
            try
            {
                var dataStatDetailList =
                    _gfcStatDal.QueryStatShopCommoditySellingInfo<T>(true, queryDateType,
                        ref totalCount, isGroupbyShop, isGroupByCommodity, isGroupByPayWay, isGroupByConsumer,
                        isGroupByDeliveryAccount, dtBeginTime, dtEndTime, shopId, orderPayWay, commodityName,
                        commodityBarCode, deliveryAccountId, consumerName, pageIndex, pageSize);
                var returnDataList = new TableDataViewDto<T>
                {
                    data = dataStatDetailList,
                    draw = draw,
                    recordsFiltered = totalCount,
                    recordsTotal = totalCount
                };
                return returnDataList;
            }
            catch (Exception ex)
            {
                _fileLog.Error("GfcStatBll | QueryStatShopCommoditySellingPage | Exception: " + ex);
                return null;
            }
        }

        /// <summary>
        /// 导出统计码云卡销售数据EXCEL
        /// 可选择 分店铺 分商品 分统计周期 分用户 分配送人员进行统计
        /// 可指定时间段 指定店铺ID 指定用户ID 指定商品ID 指定商品条形码 指定配送人员进行查询 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xlsxFilePath"></param>
        /// <param name="queryDateType">查询时间周日类别</param>
        /// <param name="isGroupbyShop">是否分店铺查询</param>
        /// <param name="isGroupByCommodity">是否分商品查询</param>
        /// <param name="isGroupByPayWay">是否分支付方式查询</param>
        /// <param name="isGroupByConsumer">是否分用户查询</param>
        /// <param name="isGroupByDeliveryAccount">是否分配送人员查询</param>
        /// <param name="dtBeginTime">开始时间</param>
        /// <param name="dtEndTime">结束时间</param>
        /// <param name="shopId">店铺ID</param>
        /// <param name="orderPayWay">支付方式</param>
        /// <param name="commodityName">商品名称</param>
        /// <param name="commodityBarCode">商品条形码</param>
        /// <param name="deliveryAccountId">配送人员ID</param>
        /// <param name="consumerName">客户名称</param>
        public bool ExportExcelStatShopCommoditySelling<T>(string xlsxFilePath,
            CommonEnum.DataStatQueryDateType queryDateType, bool isGroupbyShop = false, bool isGroupByCommodity = false,
            bool isGroupByPayWay = false, bool isGroupByConsumer = false, bool isGroupByDeliveryAccount = false,
            DateTime? dtBeginTime = null, DateTime? dtEndTime = null, int? shopId = null, int? orderPayWay = null,
            string commodityName = "", string commodityBarCode = "", int? deliveryAccountId = null,
            string consumerName = null)
        {
            if (string.IsNullOrWhiteSpace(xlsxFilePath))
            {
                return false;
            }

            if (dtBeginTime != null && dtEndTime != null)
            {
                if ((DateTime)dtBeginTime > (DateTime)dtEndTime)
                {
                    var dtTemp = dtEndTime;
                    dtEndTime = dtBeginTime;
                    dtBeginTime = dtTemp;
                }
            }

            if (deliveryAccountId != null)
            {
                isGroupByDeliveryAccount = true;
            }
            if (consumerName != null)
            {
                isGroupByConsumer = true;
            }
            if (orderPayWay != null)
            {
                isGroupByPayWay = true;
            }
            if (!string.IsNullOrWhiteSpace(commodityName) || !string.IsNullOrWhiteSpace(commodityBarCode))
            {
                isGroupByCommodity = true;
            }
            if (shopId != null)
            {
                isGroupbyShop = true;
            }

            try
            {
                var totalCount = 0;
                var dataStatDetailList = _gfcStatDal.QueryStatShopCommoditySellingInfo<T>(false, queryDateType,
                        ref totalCount, isGroupbyShop, isGroupByCommodity, isGroupByPayWay, isGroupByConsumer,
                        isGroupByDeliveryAccount, dtBeginTime, dtEndTime, shopId, orderPayWay, commodityName,
                        commodityBarCode, deliveryAccountId, consumerName);
                if (dataStatDetailList == null || dataStatDetailList.Count == 0)
                {
                    return false;
                }
                DataSet ds = new DataSet();
                ds.Tables.Add(CreateExcelFile.ListToDataTable(dataStatDetailList));
                ds.Tables[0].Columns[0].ColumnName = "客户名称";
                ds.Tables[0].Columns[1].ColumnName = "配送人员";
                ds.Tables[0].Columns[2].ColumnName = "店铺名称";
                ds.Tables[0].Columns[3].ColumnName = "商品名称";
                ds.Tables[0].Columns[4].ColumnName = "商品条形码";
                ds.Tables[0].Columns[5].ColumnName = "统计时间";
                ds.Tables[0].Columns[6].ColumnName = "商品出售量";
                ds.Tables[0].Columns[7].ColumnName = "商品单价";
                ds.Tables[0].Columns[8].ColumnName = "支付方式";
                ds.Tables[0].Columns[9].ColumnName = "商品出售总额";
                ds.Tables[0].Columns[10].ColumnName = "售卖方式";
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/")))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/"));
                }
                return CreateExcelFile.CreateExcelDocument(ds, xlsxFilePath);
            }
            catch (Exception ex)
            {
                _fileLog.Error("GfcStatBll | ExportExcelStatShopCommoditySelling | Exception: " + ex);
                return false;
            }
        }

        #endregion

        #region 订单统计报表
        /// <summary>
        /// 获取订单统计报表
        /// </summary>
        /// <param name="draw"></param>
        /// <param name="queryDateType"></param>
        /// <param name="isGroupbyShop"></param>
        /// <param name="isGroupByPayWay"></param>
        /// <param name="isGroupByOrderStatus"></param>
        /// <param name="dtBeginTime"></param>
        /// <param name="dtEndTime"></param>
        /// <param name="shopId"></param>
        /// <param name="orderPayWay"></param>
        /// <param name="orderStatus"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public TableDataViewDto<DataStatShopOrders> QueryDataStatShopOrdersPage(int draw,
            CommonEnum.DataStatQueryDateType queryDateType, bool isGroupbyShop = false, bool isGroupByPayWay = false,
            bool isGroupByOrderStatus = false, DateTime? dtBeginTime = null, DateTime? dtEndTime = null,
            int? shopId = null, int? orderPayWay = null, int? orderStatus = null, int pageIndex = 1, int pageSize = 50)
        {
            var totalCount = 0;
            pageIndex = pageIndex <= 0 ? 1 : pageIndex;
            pageSize = pageSize <= 0 ? 50 : pageSize;

            if (dtBeginTime != null && dtEndTime != null)
            {
                if ((DateTime)dtBeginTime > (DateTime)dtEndTime)
                {
                    var dtTemp = dtEndTime;
                    dtEndTime = dtBeginTime;
                    dtBeginTime = dtTemp;
                }
            }

            if (orderPayWay != null)
            {
                isGroupByPayWay = true;
            }
            if (shopId != null)
            {
                isGroupbyShop = true;
            }
            if (orderStatus != null)
            {
                isGroupByOrderStatus = true;
            }

            try
            {
                var dataStatOrdersList =
                    _gfcStatDal.QueryStatShopOrders(true, queryDateType, ref totalCount, isGroupbyShop, isGroupByPayWay,
                        isGroupByOrderStatus, dtBeginTime, dtEndTime, shopId, orderPayWay, orderStatus, pageIndex,
                        pageSize);
                var returnDataList = new TableDataViewDto<DataStatShopOrders>
                {
                    data = dataStatOrdersList,
                    draw = draw,
                    recordsFiltered = totalCount,
                    recordsTotal = totalCount
                };
                return returnDataList;
            }
            catch (Exception ex)
            {
                _fileLog.Error("GfcStatBll | QueryDataStatShopOrdersPage | Exception: " + ex);
                return null;
            }

        }

        public bool ExportExcelDataStatShopOrdersPage(string xlsxFilePath,
            CommonEnum.DataStatQueryDateType queryDateType, bool isGroupbyShop = false, bool isGroupByPayWay = false,
            bool isGroupByOrderStatus = false, DateTime? dtBeginTime = null, DateTime? dtEndTime = null,
            int? shopId = null, int? orderPayWay = null, int? orderStatus = null)
        {
            if (string.IsNullOrWhiteSpace(xlsxFilePath))
            {
                return false;
            }

            if (dtBeginTime != null && dtEndTime != null)
            {
                if ((DateTime)dtBeginTime > (DateTime)dtEndTime)
                {
                    var dtTemp = dtEndTime;
                    dtEndTime = dtBeginTime;
                    dtBeginTime = dtTemp;
                }
            }

            if (orderPayWay != null)
            {
                isGroupByPayWay = true;
            }
            if (shopId != null)
            {
                isGroupbyShop = true;
            }
            if (orderStatus != null)
            {
                isGroupByOrderStatus = true;
            }

            try
            {
                var totalCount = 0;
                var dataStatOrdersList =
                    _gfcStatDal.QueryStatShopOrders(true, queryDateType, ref totalCount, isGroupbyShop, isGroupByPayWay,
                        isGroupByOrderStatus, dtBeginTime, dtEndTime, shopId, orderPayWay, orderStatus);
                if (dataStatOrdersList == null || dataStatOrdersList.Count == 0)
                {
                    return false;
                }

                DataSet ds = new DataSet();

                ds.Tables.Add(CreateExcelFile.ListToDataTable(dataStatOrdersList));
                ds.Tables[0].Columns[0].ColumnName = "店铺名称";
                ds.Tables[0].Columns[1].ColumnName = "统计时间";
                ds.Tables[0].Columns[3].ColumnName = "订单状态描述";
                ds.Tables[0].Columns[4].ColumnName = "支付方式";
                ds.Tables[0].Columns[5].ColumnName = "订单数";
                ds.Tables[0].Columns[6].ColumnName = "订单总价";
                ds.Tables[0].Columns.RemoveAt(2);
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/")))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/Files/Statistics/"));
                }
                return CreateExcelFile.CreateExcelDocument(ds, xlsxFilePath);
            }
            catch (Exception ex)
            {
                _fileLog.Error("GfcStatBll | ExportExcelDataStatShopOrdersPage | Exception: " + ex);
                return false;
            }
        }
        #endregion

    }
}
